package com.lizhi.dingdong.apk.viewmodel

import android.app.Application
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.lizhi.dingdong.apk.data.NotificationItem
import com.lizhi.dingdong.apk.service.WebSocketService
import com.lizhi.dingdong.apk.util.FixedSizeQueue
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.jvm.java
import kotlin.toString

class NotificationViewModel(application: Application) : AndroidViewModel(application) {

    // 【重构 1】内部使用 FixedSizeQueue 来管理数据和容量限制
    private val queue: FixedSizeQueue<NotificationItem> = FixedSizeQueue(200)

    private val _uiState = MutableStateFlow<List<NotificationItem>>(emptyList())
    val uiState: StateFlow<List<NotificationItem>> = _uiState

    init {
        loadInitialData()
        startWebSocketService()
        collectWebSocketData()
    }

    // ==================== 初始数据加载 ====================
    private fun loadInitialData() {
        val initialData = createMockData() // 调用新的加载函数
        queue.addAll(initialData) // 设置初始状态
        // 发射一个新的 List 对象，触发 StateFlow 更新
        _uiState.value = queue.toList()
    }

    private fun startWebSocketService() {

        if (WebSocketService.INSTANCE != null){
            return
        }

        val context = getApplication<Application>().applicationContext
        val intent = Intent(context, WebSocketService::class.java)

        // 启动服务 (Android 12+ 需要特殊处理，这里使用基础启动)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
            Log.d("startService", "start WebSocketService")
        } else {
            context.startService(intent)
        }

        // 绑定服务以获取 Binder 和 Flow
        //context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        Log.d("NotificationViewModel","启动 WebSocketService")
    }

    private fun collectWebSocketData() {

        Log.d("NotificationViewModel-collectWebSocketData", "NotificationViewModel-collectWebSocketData")

        viewModelScope.launch {

            Log.d("NotificationViewModel", WebSocketService.Companion.currentDataFlow.toString())

            while (WebSocketService.Companion.currentDataFlow == null && this.isActive){
                delay(2000)
                Log.d("NotificationViewModel", "WebSocketService.currentDataFlow is null, waiting...")
            }

            WebSocketService.Companion.currentDataFlow?.collect { newItem ->
                Log.d("NotificationViewModel", "Received new item from MyDataService: $newItem")

                if (newItem.msgType == 0 || newItem.msgType == 1){
                    return@collect
                }

                // 更新 UI 状态
                queue.add(newItem)

                // 【关键修复】重新赋值相同的对象，强制 StateFlow 发射更新
                // 必须在修改完可变对象后执行此操作，以通知 Compose UI 数据已更改
                _uiState.value = queue.toList()
            }
        }
    }

    // 模拟添加接收到的数据，供 UI 消费
    fun addTestNotification(item: NotificationItem) {
        queue.add(item)
        _uiState.value = queue.toList()
    }

    fun addTestNotification2() {
        queue.add(NotificationItem(
            4,
            "Test",
            "Now",
            "实时更新!",
            "来自 WebSocket 的新消息",
            Color.Companion.Red.toArgb()
        ))
        Log.d("addTestNotification2","创建测试数据")
        _uiState.value = queue.toList()
    }

    private fun createMockData(): List<NotificationItem> {
        // 使用 Compose 的 Color(Int) 构造函数来创建颜色
        val blue = Color(0xFF2196F3)
        val green = Color(0xFF4CAF50)
        val purple = Color(0xFF9C27B0)
        val orange = Color(0xFFFF9800)

        return listOf(
            NotificationItem(
                5,
                "中国电信",
                "10/18",
                "【余额不足提醒】尊敬的客户...",
                "截至2025年10月18日01时59分，您的可用余额为14.90...",
                blue.toArgb()
            ),
            NotificationItem(9, "OPPO会员", "10/18", "会员购机大补贴!", null, green.toArgb()),
            NotificationItem(
                10,
                "灵犀智能助理",
                "10/18",
                "【套餐余量情况提醒】",
                null,
                purple.toArgb()
            ),
            NotificationItem(
                6,
                "中国电信",
                "10/16",
                "中西部授予陆军某合成旅...",
                "“时代楷模”称号，褒扬他们是“刘老庄连”的...",
                blue.toArgb()
            ),
            NotificationItem(
                7,
                "OPPO流量充值",
                "10/15",
                "20GB流量待领取 (1)",
                null,
                green.toArgb()
            ),
            NotificationItem(
                8,
                "招商证券",
                "10/15",
                "最新研报: 能源板块深度分析",
                "关注新能源汽车产业链的长期价值...",
                orange.toArgb()
            )
        )
    }
}